// Import necessary modules
const express = require('express');

const { login } = require("./src/api/login/index")
const { queryBalance, transfer ,trlist} = require("./src/api/hermit/tx");
const { getSessionUser } = require("./src/db/index")
const { decryptByPrivateKey } = require("./src/utils/encrypt_util")

const app = express();
app.use(express.json()); // Middleware to parse JSON bodies

const PORT = 3000;

app.post('/login', login);

app.post('/queryBalance', queryBalance);

app.post('/transfer', transfer);

app.post('/trlist', trlist);

app.post('/test', async function (req, res) {
  console.log(req.headers)
  const { sessionid } = req.headers
  if (!sessionid) {
    return res.status(400).send({ error: 'sessionId is required' });
  }

  const { data } = req.body
  if (!data) {
    return res.status(400).send({ error: 'data is required' });
  }
  try {
    const sessionUser = await getSessionUser(sessionid)
    if (!sessionUser || !sessionUser.private_key) {
      return res.status(401).send({ error: 'user unauthorized' });
    }
    
    const jsonStr = decryptByPrivateKey(sessionUser.private_key, data)

    console.log("jsonStr="+jsonStr)

    const obj = JSON.parse(jsonStr)

    res.send(obj)
  } catch (error) {
    console.error('Error test:', error);
    res.status(500).send({ error: 'Failed to test' });
  }

});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
